<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="closeRoleDialog"
    @open="openRoleDialogFn()"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <!-- label：checkbox对应的值 -->
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="commitRoleToEmployee">
        确定
      </el-button>
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getUserBaseInfo } from '@/api/user'
import { updateEmployeeRolse } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 复选框选中的值
      checkList: [],
      //   角色列表
      roleList: [],
      //   加载中
      loading: false
    }
  },
  methods: {
    // 关闭角色弹层
    closeRoleDialog() {
      this.$emit('update:showRoleDialog', false)
      // 关闭弹层的时候将角色id数组情况
      this.checkList = []
    },
    // 弹层打开时触发的操作--获取角色列表和当前用户的角色列表
    async openRoleDialogFn() {
      this.loading = true
      const { data } = await getRoleListApi(1, 9999)
      this.roleList = data.rows
      const res = await getUserBaseInfo(this.userId)
      //   console.log(res)
      // 判断一下此员工的角色id是否有值，如果没有值那就赋个初始值--初始值为员工的角色id
      if (!res.data.roleIds) {
        res.data.roleIds = ['604e2b25488be61b90b6877b']
      }
      this.checkList = res.data.roleIds
      this.loading = false
    },
    // 点击确认按钮--给员工分配角色
    async commitRoleToEmployee() {
      await updateEmployeeRolse(this.userId, this.checkList)
      // 关闭弹层
      this.closeRoleDialog()
      this.$message.success('分配角色成功')
    }
  }
}
</script>
